package top.meeting.room.module.book.controllers;

import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.log.Log;
import com.jfinal.log.Log4jLog;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xiaoleilu.hutool.date.DateUnit;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import top.jfinal.jwtTokenPlugin.interceptor.JwtTokenInterceptor;
import top.meeting.room.common.base.BaseController;
import top.meeting.room.common.kit.TimeKit;
import top.meeting.room.module.book.dto.Timer;
import top.meeting.room.module.book.dto.WeekBookData;
import top.meeting.room.module.book.forms.ApproveForm;
import top.meeting.room.module.book.forms.BookForm;
import top.meeting.room.module.book.model.Book;
import top.meeting.room.module.book.query.BookQuery;
import top.meeting.room.module.book.services.impl.BookService;
import top.meeting.room.module.system.controllers.RoleController;
import top.meeting.room.module.system.model.User;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by Lyt on 2017/9/11.
 */
@Before({JwtTokenInterceptor.class})
public class BookController extends BaseController {
    private static final Log _log = Log4jLog.getLog(RoleController.class);

    /**
     * 根据日期和查询条件查询预定记录
     */
    @Before({POST.class})
    public void find() {
        String dateStr = getPara("date");
        String params = getPara("params");
        BookQuery bookQuery = new BookQuery(dateStr);
        bookQuery.setParams(params);
        bookQuery.setStatus("1");
        List bookList = Book.handlerFind(BookService.me.findBookList(bookQuery)
                .stream().map(book -> {
                    return book.toDTO();
                }).collect(Collectors.toList()));

        for (int i = 0; i < bookList.size(); i++) {
            WeekBookData weekBookData = (WeekBookData) bookList.get(i);
            if (StrUtil.isBlank(weekBookData.getLabel())) {
                weekBookData.setLabel(TimeKit.getDayOfWeek(i));
                weekBookData.setTimer(Arrays.asList(TimeKit.getNullTimer()));
            }
            bookList.set(i, weekBookData);
        }
        renderJsonSuccess(bookList);
    }

    public void findAll() {
        String dateStr = getPara("date");
        String params = getPara("params");
        String roomId = getPara("roomId");
        Long timeMills = DateUtil.parse(dateStr).getTime();
        BookQuery bookQuery = new BookQuery();
        bookQuery.setRoomId(roomId);
        bookQuery.setParams(params);
        bookQuery.setStatus("0,1");
        bookQuery.setBookDate(timeMills);
        List bookList = Book.handlerFind(BookService.me.findBookList(bookQuery)
                .stream().map(book -> {
                    return book.toDTO();
                }).collect(Collectors.toList()));
        if (bookList == null) {
            String dayOfWeek = TimeKit.getDayOfWeek(DateUtil.dayOfWeek(DateUtil.parseDate(dateStr)));
            List result = new ArrayList();
            WeekBookData data = new WeekBookData();
            data.setTimer(TimeKit.getTimer());
            data.setLabel(dayOfWeek);
            result.add(data);
            renderJsonSuccess(result);
            return;
        }
        Iterator iterator = bookList.iterator();
        while (iterator.hasNext()) {
            WeekBookData data = (WeekBookData) iterator.next();
            if (StrUtil.isBlank(data.getLabel())) {
                iterator.remove();
            }
        }
        renderJsonSuccess(bookList);
    }

    /**
     * 查询待审批的预定
     */
    @Before({GET.class})
    public void findPendingApprovalBookList() {
        BookQuery bookQuery = new BookQuery();
        bookQuery.setStatus("0");
        List<Book> books = BookService.me.findBookList(bookQuery);
        renderJsonSuccess(books.stream().map(book -> {
            return book.toPendingApprovalBook();
        }).collect(Collectors.toList()));
    }

    /**
     * 查询当前用户所在部门暂未执行的预定记录
     */
    @Before({GET.class})
    public void findDeptBookList() {
        String findByDept = getPara("param");
        User user = getAttr("me");
        String dept = user.getDepartment();
        BookQuery bookQuery = new BookQuery();
        if ("false".equals(findByDept)) {
            bookQuery.setParams(String.valueOf(user.getId()));
            List<Book> myBooks = BookService.me.findRecordByMe(bookQuery);
            renderJsonSuccess(myBooks.stream().map(book -> {
                return book.toDeptBook();
            }).collect(Collectors.toList()));
            return;
        }
        bookQuery.setCurrTime(new Date());
        bookQuery.setStatus("1");
        bookQuery.setParams(dept);
        List<Book> books = BookService.me.findBookList(bookQuery);
        renderJsonSuccess(books.stream().map(book -> {
            return book.toDeptBook();
        }).collect(Collectors.toList()));
    }

    /**
     * 审批
     */
    @Before({GET.class, Tx.class})
    public void approve() {
        ApproveForm approveForm = getUrlParaToObj(ApproveForm.class);
        if ("暂无".equals(approveForm.getBooker())) {
            renderJsonError("预订人不存在");
            return;
        }
        User user = getAttr("me");
        approveForm.setApprover(user.getId());
        BookService.me.approveService(approveForm);
        renderJsonSuccess("审核成功");
    }

    /**
     * 取消会议
     */
    @Before({GET.class, Tx.class})
    public void cancel() {
        Long id = getParaToLong();
        BookService.me.cancel(id);
        renderJsonSuccess();
    }

    /**
     * 预定
     */
    @Before({POST.class, Tx.class})
    public void book() {
        BookForm bookForm = getJsonParaToObj(BookForm.class);
        User user = getAttr("me");
        bookForm.setUserId(user.getId());
        BookService.me.bookMeeting(bookForm);
        renderJsonSuccess("预定成功");
    }
}
